package com.molichuxing.framework.utils;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 钉钉消息发送工具类
 * 
 * @author zoumingyu
 * @date 2019年8月25日
 *
 */
public class DingTalkUtil {
	private static Logger logger = LoggerFactory.getLogger(DingTalkUtil.class);

	// 异常推送钉钉机器人url地址
	private static final String WEBHOOK_EXCEPTION_URL = "https://oapi.dingtalk.com/robot/send?access_token=c6e02d10dd379d79089867c73d4e4b59f361bac66b5b86c5e7a0f4ebefd6e83d";

	// 编码格式
	private static final String CHARSET = "UTF-8";
	private static final String CONTENT_TYPE = "application/json; charset=" + CHARSET;

	/**
	 * 发生异常时推送钉钉消息
	 * 
	 * @param content
	 *            发送消息内容
	 * @return
	 */
	public static boolean exceptionSend(String content) {
		boolean flag = true;
		try {
			HttpPost httppost = new HttpPost(WEBHOOK_EXCEPTION_URL);
			HttpResponse response = execute(httppost, content);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity(), "utf-8");
				logger.info("发生异常时推送钉钉消息结果:{}", result);
			} else {
				logger.error("发生异常时推送钉钉消息失败");
			}
		} catch (Exception e) {
			logger.error("发生异常时推送钉钉消息失败", e);
			flag = false;
		}

		return flag;
	}

	/**
	 * 发送钉钉群消息
	 * 
	 * @param dingTalkUrl
	 *            钉钉机器人url地址
	 * @param content
	 *            发送消息内容
	 * @return
	 */
	public static boolean execute(String dingTalkUrl, String content) {
		boolean flag = true;
		try {
			HttpPost httppost = new HttpPost(dingTalkUrl);
			HttpResponse response = execute(httppost, content);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity(), CHARSET);
				logger.info("发送钉钉消息结果:{}", result);
			} else {
				logger.error("发送钉钉消息失败");
			}
		} catch (Exception e) {
			logger.error("发送钉钉消息失败", e);
		}
		return flag;
	}

	private static HttpResponse execute(HttpPost httpPost, String content) throws ClientProtocolException, IOException {
		HttpClient httpClient = HttpClients.createDefault();
		httpPost.addHeader("Content-Type", CONTENT_TYPE);
		String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
		StringEntity se = new StringEntity(textMsg, CHARSET);
		httpPost.setEntity(se);
		return httpClient.execute(httpPost);
	}

}
